package cvut.fit.dpo.builder;

import java.util.Scanner;
import java.util.Stack;

import cvut.fit.dpo.arithmetic.AddOperator;
import cvut.fit.dpo.arithmetic.ArithmeticExpression;
import cvut.fit.dpo.arithmetic.IComponent;
import cvut.fit.dpo.arithmetic.NumericOperand;
import cvut.fit.dpo.arithmetic.SubstractOperator;

public class RPNBuilder extends Builder {

	@Override
	public ArithmeticExpression Build(String input) {

		Scanner sc = new Scanner(input);
		Stack<IComponent> stack = new Stack<IComponent>();

		if (sc.hasNext()) {
			while (sc.hasNext()) {
				if (sc.hasNextInt()) {
					int pom = sc.nextInt();
					stack.push(new NumericOperand(pom));
				} else {
					String operator = sc.next();
					if (operator.contains("+")) {
						IComponent right = stack.pop();
						IComponent left = stack.pop();
						stack.push(new ArithmeticExpression(new AddOperator(
								left, right)));
					} else if (operator.contains("-")) {
						IComponent right = stack.pop();
						IComponent left = stack.pop();
						stack.push(new ArithmeticExpression(
								new SubstractOperator(left, right)));
					} else
						throw new IllegalArgumentException(
								"Unsuported operand type!");
				}

			}
			if (stack.peek() instanceof NumericOperand) {
				arithmeticExpression = new ArithmeticExpression(stack.pop());
				// arithmeticExpression = new ArithmeticExpression(new
				// AddOperator(stack.pop(),new NumericOperand(0)));
			} else
				arithmeticExpression = (ArithmeticExpression) stack.pop();
		} else
			throw new IllegalArgumentException("Empty input!");
		return arithmeticExpression;
	}

}